import {
  CanActivate,
  ExecutionContext,
  Injectable,
  ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';

import { UsersService } from '../users/users.service'; // 引入 UsersService

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private usersService: UsersService,
  ) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const user = request.user; // 获取请求中的用户信息
    console.log('User info:', request.user);
    if (!user || !user.data.role) {
      throw new ForbiddenException('没有角色信息');
    }

    // 确保角色信息存在
    if (user.data.role.name !== 'ADMIN') {
      throw new ForbiddenException('没有权限访问');
    }

    return true; // 角色是管理员，允许通过
  }
}
